package com.shopping_back.serviceImpl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.mapper.*;
import com.shopping_back.pojo.dto.OrderBuyNowDTO;
import com.shopping_back.pojo.dto.OrderDTO;
import com.shopping_back.pojo.entity.*;
import com.shopping_back.pojo.vo.OrderVO;
import com.shopping_back.pojo.vo.ShipOrderVO;
import com.shopping_back.service.IOrderMainService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping_back.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 主订单表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class OrderMainServiceImpl extends ServiceImpl<OrderMainMapper, OrderMain> implements IOrderMainService {

    private final OrderMainMapper orderMainMapper;

    private final OrderItemMapper orderItemMapper;

    private final DeliveryMapper deliveryMapper;
    private final com.shopping_back.mapper.EvaluationMapper evaluationMapper;

    private final SpuMapper spuMapper;
    private final SkuMapper skuMapper;
    private final MemberService memberService;

    private final RefundRecordMapper refundRecordMapper;

    @Override
    public Page<OrderDTO> getOrders(Long userId, int page, int size) {
        Page<OrderMain> pageObj = new Page<>(page, size);
        Page<OrderMain> orderMainPage = orderMainMapper.selectPage(pageObj,
                new QueryWrapper<OrderMain>().eq("user_id", userId).orderByDesc("create_time"));

        List<OrderDTO> orderDTOPage = orderMainPage.getRecords().stream().map(orderMain -> {
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setId(orderMain.getId());
            orderDTO.setOrderSn(orderMain.getOrderSn());
            orderDTO.setTotalAmount(orderMain.getTotalAmount());
            orderDTO.setPayAmount(orderMain.getPayAmount());
            orderDTO.setStatus(orderMain.getStatus());
            orderDTO.setCreateTime(orderMain.getCreateTime());

            // Get order items
            List<OrderItem> items = orderItemMapper.selectList(
                    new QueryWrapper<OrderItem>().eq("order_id", orderMain.getId()));
            if (!items.isEmpty()) {
                OrderItem first = items.get(0);
                orderDTO.setProductName(first.getSkuName());
                orderDTO.setQuantity(first.getQuantity());
                orderDTO.setOrderItemId(first.getId());
                // 查询是否已评价
                boolean evaluated = evaluationMapper.selectCount(
                        new QueryWrapper<com.shopping_back.pojo.entity.Evaluation>()
                                .eq("order_item_id", first.getId())) > 0;
                orderDTO.setEvaluated(evaluated);
            }
            return orderDTO;
        }).collect(Collectors.toList());

        Page<OrderDTO> result = new Page<>();
        result.setRecords(orderDTOPage);
        result.setTotal(orderDTOPage.toArray().length);
        result.setCurrent(page);
        result.setSize(size);
        return result;
    }

    @Transactional
    @Override
    public OrderDTO buyNow(OrderBuyNowDTO dto, Long userId) {
        BigDecimal discountRate = memberService.getMemberDiscount(userId);
        // 1. 查询SKU
        System.out.println(dto.getSkuId());
        Sku sku = skuMapper.selectSkuById(dto.getSkuId());
        if (sku == null) {
            throw new RuntimeException("商品不存在");
        }
        Spu spu = spuMapper.selectById(sku.getSpuId());
        if (spu == null) {
            throw new RuntimeException("商品SPU不存在");
        }
        if (sku.getStock() < dto.getQuantity()) {
            throw new RuntimeException("库存不足");
        }

        // 2. 计算折后价格（修改点）
        BigDecimal originalAmount = sku.getPrice().multiply(BigDecimal.valueOf(dto.getQuantity()));
        BigDecimal actualAmount = originalAmount.multiply(discountRate); // 应用折扣
        Long merchantId = spu.getMerchantId();
        // 2. 创建订单主表
        OrderMain order = new OrderMain();
        order.setUserId(userId);
        order.setMerchantId(merchantId);
        order.setStatus(0); // 待支付
        order.setOrderSn(UUID.randomUUID().toString().replace("-", ""));
        order.setTotalAmount(originalAmount);
        order.setPayAmount(actualAmount);
        order.setPromotionAmount(originalAmount.subtract(actualAmount));
        baseMapper.insert(order);
        // 3. 创建订单项
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setSkuId(sku.getId());
        orderItem.setSkuName(spu.getTitle());
        orderItem.setSkuPrice(sku.getPrice());
        orderItem.setQuantity(dto.getQuantity());
        orderItem.setSubTotal(sku.getPrice().multiply(BigDecimal.valueOf(dto.getQuantity())));
        orderItemMapper.insert(orderItem);
        // 4. 扣减库存
        sku.setStock(sku.getStock() - dto.getQuantity());
        skuMapper.updateSkuStock(sku.getId(), sku.getStock());
        // 5. 返回结果
        OrderDTO result = new OrderDTO();
        result.setId(order.getId());
        result.setOrderSn(order.getOrderSn());
        result.setProductName(orderItem.getSkuName());
        result.setQuantity(orderItem.getQuantity());
        result.setTotalAmount(order.getTotalAmount());
        result.setStatus(order.getStatus());
        result.setCreateTime(order.getCreateTime());
        result.setOrderItemId(orderItem.getId());
        result.setEvaluated(false);
        return result;
    }


    @Transactional
    public void payOrder(Long orderId) {
        OrderMain order = orderMainMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 0) {
            throw new RuntimeException("订单状态不允许支付");
        }
        order.setStatus(1); // 待发货
        order.setPaymentTime(LocalDateTime.now());
        orderMainMapper.updateById(order);
    }

    @Transactional
    public void cancelOrder(Long orderId) {
        OrderMain order = orderMainMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 0) {
            throw new RuntimeException("订单状态不允许取消");
        }
        order.setStatus(4); // 已取消
        orderMainMapper.updateById(order);
    }

    @Transactional
    public void refundOrder(Long orderId) {
        OrderMain order = orderMainMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!Arrays.asList(1, 2, 3).contains(order.getStatus())) {
            throw new RuntimeException("订单状态不允许退款");
        }
        order.setStatus(5); // 待退款
        orderMainMapper.updateById(order);
        RefundRecord refundRecord = new RefundRecord();
        refundRecord.setPaymentId(orderId); // 设置默认值0，表示系统生成
        refundRecord.setRefundSn(order.getOrderSn());
        refundRecord.setRefundAmount(order.getPayAmount());
        refundRecord.setStatus(0);
        refundRecord.setReason("用户申请退款");
        refundRecord.setCreateTime(order.getCreateTime());
        refundRecord.setUpdateTime(order.getUpdateTime());
        refundRecordMapper.insert(refundRecord);

    }

    @Transactional
    public void deleteOrder(Long orderId) {
        OrderMain order = orderMainMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 4) {
            throw new RuntimeException("仅允许删除已取消的订单");
        }
        orderMainMapper.deleteById(orderId);
        orderItemMapper.delete(new QueryWrapper<OrderItem>().eq("order_id", orderId));
    }

    @Override
    public Page<OrderVO> getMerchantOrders(Long merchantId, Integer page, Integer size) {
        Page<OrderMain> orderPage = new Page<>(page, size);
        LambdaQueryWrapper<OrderMain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderMain::getMerchantId, merchantId)
                .orderByDesc(OrderMain::getId);

        Page<OrderMain> result = this.page(orderPage, queryWrapper);

        // 转换为前端需要的VO
        Page<OrderVO> voPage = new Page<>();
        voPage.setTotal(result.getTotal());
        voPage.setRecords(result.getRecords().stream().map(order -> {
            OrderVO vo = new OrderVO();
            vo.setId(order.getId());
            vo.setOrderSn(order.getOrderSn());
            vo.setPayAmount(order.getPayAmount());
            vo.setStatus(order.getStatus());

            // 获取订单明细
            List<OrderItem> items = orderItemMapper.selectByOrderId(order.getId());
            vo.setItems(items);

            // 假设每个订单只展示第一个商品名称
            if (!items.isEmpty()) {
                vo.setSkuName(items.get(0).getSkuName());
            }

            OrderMain orderItem = orderMainMapper.selectById(order.getId());
            vo.setPaymentStatus(orderItem != null ? orderItem.getStatus() : 0);

            Delivery delivery = deliveryMapper.selectById(order.getId());
            vo.setLogisticsStatus(delivery != null ? delivery.getStatus() : 0);
            vo.setReceiverInfo(delivery != null ? delivery.getReceiverInfo() : "{}");
            vo.setDeliverySn(delivery != null ? delivery.getDeliverySn() : "");

            return vo;
        }).collect(Collectors.toList()));

        return voPage;
    }

    @Transactional
    public void shipOrder(ShipOrderVO request) {
        // 更新订单状态
        OrderMain order = getById(request.getOrderId());
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getStatus() != 1) {
            throw new RuntimeException("订单状态不允许发货");
        }
        order.setStatus(2); // 已发货
        updateById(order);

        // 更新物流信息
        Delivery delivery = deliveryMapper.selectById(request.getOrderId());
        if (delivery == null) {
            delivery = new Delivery();
            delivery.setOrderId(request.getOrderId());
            delivery.setDeliverySn(request.getDeliverySn());
            delivery.setStatus(1); // 运输中
            delivery.setShippingTime(LocalDateTime.now());
            deliveryMapper.insert(delivery);
        } else {
            delivery.setDeliverySn(request.getDeliverySn());
            delivery.setStatus(1); // 运输中
            delivery.setShippingTime(LocalDateTime.now());
            deliveryMapper.updateById(delivery);
        }
    }

    /**
     * 创建“已支付‑未成团”的拼团订单（status = -1）
     */
    @Transactional
    public OrderMain createPaidGroupOrder(Long userId,
                                          Long groupId,
                                          Sku sku,
                                          Spu spu,
                                          int quantity,
                                          BigDecimal groupPrice) {

        OrderMain order = new OrderMain();
        order.setUserId(userId);
        order.setMerchantId(spu.getMerchantId());
        order.setStatus(-1);                       // 已支付未成团
        order.setOrderSn(UUID.randomUUID().toString().replace("-", ""));
        BigDecimal total = groupPrice.multiply(BigDecimal.valueOf(quantity));
        order.setTotalAmount(total);
        order.setPayAmount(total);
        order.setPromotionAmount(BigDecimal.ZERO);
        orderMainMapper.insert(order);

        OrderItem oi = new OrderItem();
        oi.setOrderId(order.getId());
        oi.setSkuId(sku.getId());
        oi.setSkuName(spu.getTitle());
        oi.setSkuPrice(groupPrice);
        oi.setQuantity(quantity);
        oi.setSubTotal(total);
        orderItemMapper.insert(oi);

        return order;
    }


}
